package com.estar.integaration.Controller.paymentPlanController;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.estar.integaration.Reader.SupplierAccountPeriodReader;
import com.estar.integaration.Service.paymentPlanService.IPurchaseOrderDetailService;
import com.estar.integaration.Service.paymentPlanService.ISupplierAccountPeriodService;
import com.estar.integaration.Util.FileUtil;
import com.estar.integaration.Util.Util;
import com.estar.integaration.entity.NoSQL.Res;
import com.estar.integaration.entity.paymentPlanEntity.ReceiptComeLedger;
import com.estar.integaration.entity.paymentPlanEntity.SupplierAccountPeriod;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.Vector;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author YJL
 * @since 2022-02-15
 */
@RestController
@RequestMapping("/supplier-account-period")
public class SupplierAccountPeriodController {
  @Value("${spring.profiles.active}")
  private String mEnvironment;

  @Autowired
  private ISupplierAccountPeriodService supplierAccountPeriodService;

  @Autowired
  private IPurchaseOrderDetailService purchaseOrderDetailService;

  @PostMapping("/import-supplier-account-period")
  @ResponseBody
  public Res importExcel(HttpServletRequest request) {
    String folderAddress = mEnvironment.equals("dev") ? "D:\\SCM_file\\paymentPlan\\supplierAccountPeriod" : "/root/excel/paymentPlan/supplierAccountPeriod";
//    String folderAddress = "/root/excel/inventoryFile/inventoryAge";
    //删除原文件夹全部文件
    Util.deleteAllFile(new File(folderAddress));
    //添加进去新文件
    MultipartHttpServletRequest params = (MultipartHttpServletRequest) request;
    List<MultipartFile> multipartFiles = params.getFiles("files");
    Vector<String> multipartFilePath = new Vector<>();//上传文件的地址
    for (MultipartFile file : multipartFiles) {
      //文件写入本地
      String address = Util.writePaymentFile2Local(file,folderAddress);
      multipartFilePath.add(address);
    }
    //用于更新List
    List<SupplierAccountPeriod> supplierAccountPeriodListfromFile = readSupplier(folderAddress);
    List<SupplierAccountPeriod> supplierAccountPeriodListfromDB = supplierAccountPeriodService.getAllSupplierAccountPeriod();
    List<SupplierAccountPeriod> diffList = updateAllDBListfromFileList(supplierAccountPeriodListfromFile,supplierAccountPeriodListfromDB);
    supplierAccountPeriodService.saveBatch(diffList);//保存File里面新增的
    return new Res("20000","当前新增" + String.valueOf(diffList.size()) + "条数据");//上传成功
  }


  @PostMapping("/insert_supplier")
  @ResponseBody
  public Res insertSupplier(@RequestBody JSONObject jsonObject){
    String supplierName = jsonObject.getString("sName");
    String accountPeriod = jsonObject.getString("aPe");
    String needAddDay = jsonObject.getString("needAD");
    if(needAddDay == null || needAddDay.equals("")){
      needAddDay = "-1";
    }

    SupplierAccountPeriod supplierAccountPeriod = new SupplierAccountPeriod(Util.getUUID(),supplierName,accountPeriod,needAddDay,null);
    supplierAccountPeriodService.save(supplierAccountPeriod);
    List<SupplierAccountPeriod> supplierAccountPeriodList = supplierAccountPeriodService.getAllSupplierAccountPeriod();
    return new Res("20000",new Gson().toJson(supplierAccountPeriodList));
  }

  /**
   * 从文件读取出新的List,和DBList进行取差集
   */
  private List<SupplierAccountPeriod> updateAllDBListfromFileList(List<SupplierAccountPeriod> fileList,List<SupplierAccountPeriod> dbList){
    //fileList新增的则插入即可,原有的不动即可
    //TODO 加上一个筛选功能，筛选出来修改
    //fileList一定更长
    List<SupplierAccountPeriod> resultList = fileList.stream()
        .filter(item -> !dbList.stream().map(e-> e.getSupplierName()).collect(Collectors.toList()).contains(item.getSupplierName()))
        .collect(Collectors.toList());
    return resultList;
  }


  /**
   * 获得所有的供应商账期
   */
  @GetMapping("/get-all-supplier-account-period")
  public Res getAllSupplerAccountPeriod(){
    return new Res("20000",new Gson().toJson(supplierAccountPeriodService.getAllSupplierAccountPeriod()));
  }

  /**
   * 更新需加天数
   */
  @PostMapping("/update-need-add-day")
  public Res updateSupplierRealAddDay(@RequestBody JSONObject jsonObject){
    //获取更新的天数,更新到DB中
    Integer day = jsonObject.getInteger("day");
    String sName = jsonObject.getString("sName");
    supplierAccountPeriodService.updateDayBySuppliername(sName,day);
    return new Res("20000","修改成功");
  }

  @PostMapping("/filter_supplier")
  public Res filterSupplier(@RequestBody JSONObject jsonObject){
    String sName = jsonObject.getString("supName");
    List<SupplierAccountPeriod> supplierAccountPeriodList = null;
    if(sName== null || sName.equals("")){
      supplierAccountPeriodList = supplierAccountPeriodService.getAllSupplierAccountPeriod();
    }else {
      supplierAccountPeriodList = supplierAccountPeriodService.getSupplierByName(sName);
    }
    return new Res("20000",new Gson().toJson(supplierAccountPeriodList));
  }

  /**
   * 读取供应商账期
   * @param folderAddress
   * @return
   */
  private List<SupplierAccountPeriod> readSupplier(String folderAddress){
    List fileList = FileUtil.getFilesinFolder(folderAddress);
    SupplierAccountPeriodReader reader = new SupplierAccountPeriodReader(fileList);
    List<SupplierAccountPeriod> list = reader.readDueSupplierAPR();
    return list;
  }



}
